<?php

namespace App\ApiFrontend;

use App\Http\Controllers\ApiBaseController;
use App\Models\UserModel;
use Illuminate\Support\Facades\Hash;

/**
 *  登陆
 */
class Login extends ApiBaseController
{
  private array $allowTypeArr = [
    'username',//用户名
    'wechatOpenid', //微信
    'wechatOpenidMp', //微信小程序
  ];

  /**
   * 参数检查
   */
  protected function check(): void
  {
    $loginType = request('type') ?? 'username';
    if (!in_array($loginType, $this->allowTypeArr)) {
      $this->result["code"] = 1;
      $this->result["message"] = '预检: 登录模式不正确';
      return;
    }
    // 规则
    $ruleArr = [];
    switch ($loginType) {
      case 'username':
        $ruleArr['username'] = 'required';
        $ruleArr['password'] = 'required';
        break;
      case 'wechatOpenid':
        $ruleArr['wechatOpenid'] = 'required';
        break;
      case 'wechatOpenidMp':
        $ruleArr['wechatOpenidMp'] = 'required';
        break;
    }
    try {
      request()->validate($ruleArr);
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = $exception->getMessage();
    }
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    // dump(Hash::make('123456'));
    $type = request('type') ?? 'username';
    $openid = \request('openid');
    $username = \request('username');
    try {
      $selectField = [
        "userId",
        "username",
        "password",
        // "phone",
        "groupId",
        "status",
      ];

      if ($type == 'openid') {
        $user = UserModel::where('wechatOpenid', $openid)->select($selectField)->first();
        if (empty($user)) {//注册
          $userAdd = new UserModel();
          $userAdd->username = $openid;
          $userAdd->wechatOpenid = $openid;
          $userAdd->status = 1;
          $userAdd->save();
          $user = UserModel::where('wechatOpenid', $openid)->select($selectField)->first();
        }
      } else {
        $user = UserModel::where('username', $username)->select($selectField)->first();
        if (empty($user)) {
          throw new \Exception("账号不存在");
        } elseif (!Hash::check(\request('password'), $user->password)) {
          throw new \Exception("用户密码错误");
        }
      }
      //状态检测
      if ($user->status <= 0) {
        throw new \Exception("该账号已禁用, 请联系客服");
      }
      //删除之前token
      $user->destroyAuthTokens();
      $this->result['data'] = [
        // 'userId' => $user->id,
        'token' => $user->getAuthToken(),
        'username' => $user->username,
        'groupName' => \DB::table('member_group')->where('id', $user->groupId)->value('name'),
        'point' => \DB::table('member')->where('userId', $user->userId)->value('point'),
        // 'openid' => $openid,
        //'nickname' => $user->nickname,
        // 'headImg' => $user->headimg,
      ];

      //登录日志
      // $requestLog = [
      //     "ip" => request()->ip(),
      //     "userAgent" => request()->header("user-agent"),
      // ];
      // AdminLoginLogJob::dispatch($user, (object)$requestLog);//->onQueue('log');
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = $exception->getMessage();
    }

    return;
  }
}
